import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/model/image_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:direct_link/direct_link.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_electroncheckrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/models/odoo/product_electroncheckrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import '../../../generated/l10n.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';

class ProductElectroncheckrecordEdit extends StatefulWidget {
  ProductElectroncheckrecordEdit({this.productElectroncheckrecord, this.isooa});

  final bool? isooa;
  final ProductElectroncheckrecord? productElectroncheckrecord;

  @override
  _ProductElectroncheckrecordEditState createState() =>
      _ProductElectroncheckrecordEditState();
}

class _ProductElectroncheckrecordEditState
    extends State<ProductElectroncheckrecordEdit> {
  late ProductElectroncheckrecord productElectroncheckrecord;
  bool? isAdd;

  PickedFile? pickedFile;
  final ImagePicker imagePicker = ImagePicker();
  ImageModel imageModel = ImageModel();
  Uint8List? imageBytes;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<FormState> formKey2 = GlobalKey<FormState>();

  //late List<SelectOptionVO> activeList;

  //工厂名称
  List<SelectOptionVO> factoryIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];
  //设备工位
  List<SelectOptionVO> stationIdList = [];
  //问题类别
  List<SelectOptionVO> questiontypeIdList = [];

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.productElectroncheckrecord == null;
    this.productElectroncheckrecord =
        widget.productElectroncheckrecord ?? ProductElectroncheckrecord();
    if (widget.isooa!) {
      this.productElectroncheckrecord.status = '1';
    } else {
      this.productElectroncheckrecord.status = '0';
    }
    _loadSelectVO();
  }

//选择图片
  pickImage(ImageSource source) async {
    pickedFile = await imagePicker.getImage(source: source);
    if (pickedFile == null) {
      return;
    }
    imageBytes = await pickedFile!.readAsBytes();
    //限制图片大小
    if (imageBytes!.length > 1024 * 1024 * 20) {
      cryAlert(context, S.of(context).sizeLimit);
      pickedFile = null;
      imageBytes = null;
      setState(() {});
      return;
    }
    print(pickedFile!.path);

    setState(() {
      formKey.currentState!.save();
      if (widget.isooa!) formKey2.currentState!.save();
    });
  }

  _loadSelectVO() async {
    productElectroncheckrecord.checkdate =
        DateFormat('yyyy-MM-dd').format(DateTime.now());
    //工厂名称
    factoryIdList = await DynamicDataApi.getModelSelect(
        model: "hr.department",
        name: "complete_name",
        key: 'parent_id',
        val: null);
    //车间名称
    //  workshopIdList = await DynamicDataApi.getDictList("workshop_id");

    //设备工位
    // stationIdList = await DynamicDataApi.getDictList("station_id");

    //问题类别
    questiontypeIdList = await DynamicDataApi.getDictList("questiontype");

    if (productElectroncheckrecord.workshopId != null) {
      workshopIdList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "hr.department",
          name: "complete_name",
          key: 'parent_id',
          val: int.parse(this.productElectroncheckrecord.factoryId!));
    }
    if (productElectroncheckrecord.stationId != null) {
      stationIdList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "base.productionstation",
          name: "stationname",
          key: 'workshop_id',
          val: int.parse(this.productElectroncheckrecord.workshopId!));
    }

    //activeList=[SelectOptionVO(value:'0',label: "禁用"),SelectOptionVO(value:'1',label: "启用")];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var ooa = Form(
      key: formKey2,
      child: Wrap(
        children: <Widget>[
          SizedBox(
            height: 30,
          ),
          Divider(
            color: Colors.black,
            height: 5,
            thickness: 10,
            // indent: 15.0,
            // endIndent: 15.0,
          ),
          Center(
            child: Text(
              "请填写以下信息",
              style: TextStyle(color: Colors.red),
            ),
          ),
          CryInput(
            label: '原因分析',
            value: productElectroncheckrecord.causeanalysis,
            onSaved: (v) {
              productElectroncheckrecord.causeanalysis = v;
            },
          ),
          CryInput(
            label: '整改措施',
            value: productElectroncheckrecord.rectificationmeasures,
            onSaved: (v) {
              productElectroncheckrecord.rectificationmeasures = v;
            },
          ),
          CryInput(
            label: '有效验证',
            value: productElectroncheckrecord.effectiveverification,
            onSaved: (v) {
              productElectroncheckrecord.effectiveverification = v;
            },
          ),
        ],
      ),
    );

    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          widget.isooa!
              ? CryInput(
                  label: '检查日期',
                  value: productElectroncheckrecord.checkdate,
                  onSaved: (v) {
                    productElectroncheckrecord.checkdate = v;
                  },
                  enable: false,
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                )
              : CrySelectDate(
                  context,
                  label: '检查日期',
                  value: productElectroncheckrecord.checkdate,
                  onSaved: (v) {
                    productElectroncheckrecord.checkdate = v;
                  },
                ),
          widget.isooa!
              ? CryInput(
                  label: '工厂名称',
                  value: productElectroncheckrecord.factoryName,
                  enable: false,
                )
              : CrySelect(
                  label: '工厂名称',
                  dataList: factoryIdList,
                  value: productElectroncheckrecord.factoryId,
                  onSaved: (v) => {productElectroncheckrecord.factoryId = v},
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                  onChange: (v) async {
                    if (productElectroncheckrecord.factoryId != v) {
                      formKey.currentState!.save();
                      if (widget.isooa!) formKey2.currentState!.save();
                      productElectroncheckrecord.factoryId = v;
                      productElectroncheckrecord.workshopId = null;
                      stationIdList = [];
                      try {
                        workshopIdList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "hr.department",
                            name: "complete_name",
                            key: 'parent_id',
                            val: int.parse(v));
                      } catch (e) {
                        workshopIdList = [];
                      }
                      setState(() {});
                    }
                  },
                ),
          widget.isooa!
              ? CryInput(
                  label: '车间名称',
                  value: productElectroncheckrecord.workshopName,
                  enable: false,
                )
              : CrySelect(
                  label: '车间名称',
                  dataList: workshopIdList,
                  value: productElectroncheckrecord.workshopId,
                  onSaved: (v) => {productElectroncheckrecord.workshopId = v},
                  onChange: (v) async {
                    if (productElectroncheckrecord.workshopId != v) {
                      formKey.currentState!.save();
                      if (widget.isooa!) formKey2.currentState!.save();
                      productElectroncheckrecord.workshopId = v;
                      productElectroncheckrecord.stationId = null;
                      try {
                        stationIdList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "base.productionstation",
                            name: "stationname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        stationIdList = [];
                      }
                      setState(() {});
                    }
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
          widget.isooa!
              ? CryInput(
                  label: '设备工位',
                  value: productElectroncheckrecord.stationName,
                  enable: false,
                )
              : CrySelect(
                  label: '设备工位',
                  dataList: stationIdList,
                  value: productElectroncheckrecord.stationId,
                  onSaved: (v) => {productElectroncheckrecord.stationId = v},
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
          widget.isooa!
              ? CryInput(
                  label: '问题类别',
                  value: productElectroncheckrecord.questiontypeName,
                  enable: false,
                )
              : CrySelect(
                  label: '问题类别',
                  dataList: questiontypeIdList,
                  value: productElectroncheckrecord.questiontypeId,
                  onSaved: (v) =>
                      {productElectroncheckrecord.questiontypeId = v},
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
          // CryInput(
          //   label: '上传图片',
          //   value: productElectroncheckrecord.uploadimg,
          //   onSaved: (v) {
          //     productElectroncheckrecord.uploadimg = v;
          //   },
          // ),
          CryInput(
            label: '问题描述',
            value: productElectroncheckrecord.questiondescription,
            onSaved: (v) {
              productElectroncheckrecord.questiondescription = v;
            },
            enable: widget.isooa! ? false : true,
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          Column(
              // alignment: Alignment.center,
              children: [
                //mainAxisAlignment: Alignment.center,

                CryButton(
                  label: '上传图片',
                  iconData: Icons.photo,
                  onPressed: widget.isooa!
                      ? null
                      : () => pickImage(ImageSource.gallery),
                ),

                Center(
                  child: Text(
                    "上传图片大小不超过20M",
                    style: TextStyle(color: Colors.red),
                  ),
                ),
                SizedBox(
                  width: 30,
                ),
                previewImage(productElectroncheckrecord.uploadimg)
              ]),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();

            if (widget.isooa!) {
              FormState form2 = formKey2.currentState!;
              form2.save();
            }

            if (pickedFile != null) {
              productElectroncheckrecord.uploadimg = base64Encode(imageBytes!);
            }
            if (widget.isooa!) {
              productElectroncheckrecord.handleuserId =
                  StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]['user_id']
                          [0]
                      .toString();

              DateTime now = new DateTime.now();
              productElectroncheckrecord.handledatetime =
                  DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
            }
            ProductElectroncheckrecordOdooApi.saveOrUpdate(
                    productElectroncheckrecord.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(widget.isooa!
            ? '处理'
            : isAdd!
                ? S.of(context).add
                : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            form,
            widget.isooa! ? ooa : Container(),
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );

    // return result;
  }

//回显图片
  Widget previewImage(String? img) {
    // return Image.memory(imageBytes!);
    if (img != null) {
      return Image.memory(
        base64Decode(productElectroncheckrecord.uploadimg!),
        width: 100,
        height: 100,
      );
    } else {
      if (pickedFile != null) {
        if (kIsWeb) {
          return Image.memory(
            imageBytes!,
            width: 100,
            height: 100,
          );
        } else {
          return Image.file(File(pickedFile!.path));
        }
      } else {
        return Container();
      }
    }
  }
}
